package com.liuwa.openapi.common;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liuwa.common.bean.BasePageQuery;
import com.liuwa.common.bean.Page;
import com.liuwa.common.bean.SortedPageQuery;
import com.liuwa.common.core.page.PageDomain;
import com.liuwa.common.core.page.TableSupport;
import com.liuwa.common.utils.DateUtils;
import com.liuwa.common.utils.StringUtils;
import com.liuwa.common.utils.sql.SqlUtil;
import com.liuwa.knowledge.domain.User;
import com.liuwa.openapi.service.OpenapiTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 * 
 * @author liuwa
 */
public class BaseController
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OpenapiTokenService openapiTokenService;

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtils.parseDate(text));
            }
        });
    }



    protected void startPage(BasePageQuery query){
        Integer pageNum = query.getPage();
        Integer pageSize = query.getSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = null;
            if(query instanceof SortedPageQuery){
                orderBy  = ((SortedPageQuery)query).getOrderByString();
            }
            orderBy = SqlUtil.escapeOrderBySql(orderBy);
            Boolean reasonable = true;
            com.github.pagehelper.Page page = PageHelper.startPage(pageNum, pageSize, orderBy);
            page.setReasonable(reasonable);
            if(pageSize == 0){
                page.setPageSizeZero(true);
            }
        }
    }

    /**
     * 设置请求排序数据
     */
    protected void startOrderBy()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }




    /**
     * 响应请求分页数据
     */

    protected <T> Page<T> getPage(List<T> list, BasePageQuery query)
    {
        Page<T> page = new Page<T>(query.getPage(), query.getSize());
        page.setItems(list);
        page.setTotal(new PageInfo(list).getTotal());
        return page;
    }



    /**
     * 页面跳转
     */
    public String redirect(String url)
    {
        return StringUtils.format("redirect:{}", url);
    }

    /**
     * 获取用户缓存信息
     */
    public User getLoginUser()
    {
        return openapiTokenService.getLoginUser();
    }

    /**
     * 获取登录用户id
     */
    public Long getUserId()
    {
        return getLoginUser().getUserId();
    }


    /**
     * 获取登录用户名
     */
    public String getUsername()
    {
        return getLoginUser().getUsername();
    }
}
